package com.wsyu.springbootbackend.core.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.Collection;
import java.util.Map;

/**
 * 基于Jackson的链式JSON构建工具类
 */
public class JsonBuilder {
    // Jackson核心对象
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    // 当前操作的JSON节点
    private final ObjectNode currentNode;

    // 私有构造器，通过静态方法创建实例
    private JsonBuilder() {
        this.currentNode = OBJECT_MAPPER.createObjectNode();
    }

    // 静态工厂方法，创建新的构建器实例
    public static JsonBuilder create() {
        return new JsonBuilder();
    }

    // 添加字符串类型字段
    public JsonBuilder add(String key, String value) {
        currentNode.put(key, value);
        return this;
    }

    // 添加整数类型字段
    public JsonBuilder add(String key, int value) {
        currentNode.put(key, value);
        return this;
    }

    // 添加长整数类型字段
    public JsonBuilder add(String key, long value) {
        currentNode.put(key, value);
        return this;
    }

    // 添加布尔类型字段
    public JsonBuilder add(String key, boolean value) {
        currentNode.put(key, value);
        return this;
    }

    // 添加浮点数类型字段
    public JsonBuilder add(String key, double value) {
        currentNode.put(key, value);
        return this;
    }

    // 添加对象类型字段
    public JsonBuilder add(String key, Object value) {
        try {
            // 将对象转换为JsonNode并添加
            JsonNode node = OBJECT_MAPPER.valueToTree(value);
            currentNode.set(key, node);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("无法将对象转换为JSON节点: " + value, e);
        }
        return this;
    }

    // 添加集合类型字段
    public JsonBuilder add(String key, Collection<?> collection) {
        ArrayNode arrayNode = OBJECT_MAPPER.createArrayNode();
        for (Object item : collection) {
            arrayNode.addPOJO(item);
        }
        currentNode.set(key, arrayNode);
        return this;
    }

    // 添加子JSON对象（使用另一个JsonBuilder）
    public JsonBuilder add(String key, JsonBuilder subBuilder) {
        currentNode.set(key, subBuilder.currentNode);
        return this;
    }

    // 添加Map作为子对象
    public JsonBuilder add(String key, Map<?, ?> map) {
        try {
            JsonNode node = OBJECT_MAPPER.valueToTree(map);
            currentNode.set(key, node);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("无法将Map转换为JSON节点", e);
        }
        return this;
    }

    // 创建并返回一个新的数组构建器
    public ArrayBuilder createArray(String key) {
        return new ArrayBuilder(this, key);
    }

    // 构建为紧凑的JSON字符串
    public String build() {
        return currentNode.toString();
    }

    // 构建为格式化的JSON字符串（便于阅读）
    public String buildPretty() {
        try {
            return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(currentNode);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("生成格式化JSON失败", e);
        }
    }

    // 获取当前的ObjectNode（用于高级操作）
    public ObjectNode getObjectNode() {
        return currentNode;
    }

    /**
     * 数组构建器，用于处理JSON数组
     */
    public static class ArrayBuilder {
        private final JsonBuilder parentBuilder;
        private final String arrayKey;
        private final ArrayNode arrayNode;

        private ArrayBuilder(JsonBuilder parentBuilder, String arrayKey) {
            this.parentBuilder = parentBuilder;
            this.arrayKey = arrayKey;
            this.arrayNode = OBJECT_MAPPER.createArrayNode();
        }

        // 向数组添加元素
        public ArrayBuilder add(String value) {
            arrayNode.add(value);
            return this;
        }

        public ArrayBuilder add(int value) {
            arrayNode.add(value);
            return this;
        }

        public ArrayBuilder add(long value) {
            arrayNode.add(value);
            return this;
        }

        public ArrayBuilder add(boolean value) {
            arrayNode.add(value);
            return this;
        }

        public ArrayBuilder add(double value) {
            arrayNode.add(value);
            return this;
        }

        public ArrayBuilder add(Object value) {
            arrayNode.addPOJO(value);
            return this;
        }

        // 向数组添加子JSON对象
        public ArrayBuilder add(JsonBuilder builder) {
            arrayNode.add(builder.currentNode);
            return this;
        }

        // 完成数组构建，返回父构建器
        public JsonBuilder endArray() {
            parentBuilder.currentNode.set(arrayKey, arrayNode);
            return parentBuilder;
        }
    }
}